package cn.org.donald.framework.util;

import cn.org.donald.framework.constant.HttpMethodConstant;
import cn.org.donald.framework.constant.HttpStatus;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * @author : Donald
 * @since : 2021/1/23 9:48
 */
public class HttpUtil {

    public static String post(String url, String json){
        HttpURLConnection conn;
        OutputStream out;
        byte[] param = new byte[0];
        if (json != null){
            param = json.getBytes();
        }
        String result = null;
        try {
            URL url1 = new URL(url);
            conn = (HttpURLConnection) url1.openConnection();
            conn.setRequestMethod(HttpMethodConstant.POST);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            out = conn.getOutputStream();
            out.write(param);
            out.flush();
            out.close();
            result = StringUtil.inputStreamToString(
                    HttpStatus.OK == conn.getResponseCode()
                            ?conn.getInputStream()
                            :conn.getErrorStream(), StandardCharsets.UTF_8);
        } catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
}
